import { Modal } from 'antd';
import { WeaTools } from 'ecCom';
import { message } from 'antd'
import window from '.';
import jQuery from "jquery";

export const replaceUrl = (url: string): string => {
    if (!url) return url;
    return url.replace('/spa/formmode#/formmode/card', '/spa/cube/index.html#/main/cube/card')
        .replace('/spa/formmode/index.html#/formmode/card', '/spa/cube/index.html#/main/cube/card')
        .replace('/spa/formmode/index.html#/formmode/replyPage', '/spa/cube/index.html#/main/cube/reply')
        .replace('/formmode/view/formModeComTab.jsp', '/spa/cube/index.html#/main/cube/reply')
        .replace('/formmode/view/FormModeMap.jsp', '/spa/cube/index.html#/main/cube/map')
}

/**
 * 布局init之后对布局js部分渲染
 */
export const initJs = (loading, rightmenu, mainFields, modeField, type) => {
    if (loading != "loading") {
        //加载之前先要清除掉之前的布局的js
        jQuery("#initJs").remove();
        jQuery("[id^=layoutScript]").remove();

        let script = document.createElement('script');
        script.type = "text/javascript";
        script.id = "initJs";
        let initJs = "";

        //加载按钮js
        let urlMap = rightmenu ? rightmenu.url : {};
        if (urlMap) {
            for (let item in urlMap) {
                let hreftarget = urlMap[item].hreftarget;
                hreftarget = hreftarget.replace("/formmode/search/CustomSearchBySimple.jsp?customid=", "/spa/cube/index.html#/main/cube/search?customid=");
                hreftarget = hreftarget.replace("/formmode/view/AddFormMode.jsp", "/spa/cube/index.html#/main/cube/card");
                hreftarget = hreftarget.replace("/formmode/view/formModeComTab.jsp", "/spa/formmode/index.html#/formmode/replyPage");
                hreftarget = hreftarget.replace('/formmode/view/FormModeMap.jsp', '/spa/cube/index.html#/main/cube/map');
                //hreftarget = hreftarget.replace("/formmode/view/formModeComTab.jsp", "/#/replyPage");
                initJs += ("let url_id_" + item + " = \"" + hreftarget + "\";");
            }
        }
        //加载必填js  已废弃
        if (mainFields) {
            let needCheckStr = "";
            for (let item in mainFields) {
                let ismandatory = mainFields[item].ismandatory;
                if (ismandatory == "1") {
                    needCheckStr += (",field" + item);
                }
            }
            initJs += ("let needcheck=\"" + needCheckStr + "\";");
        }
        initJs += "let page;let util;"
        script.innerHTML = initJs;
        document.body.appendChild(script);

        /*page = objthis;
        //使用了modeForm公共方法内容  暂时去掉等待后面重新确认方式后再加回来
        let type = objthis.props.type;
        let showReply = objthis.props.showReply;
        if (showReply && type == "0") {//如果是显示布局 并且开启了回复评论 给页面主体表单以及底部评论列表绑定点击隐藏评论区域事件
            jQuery("#modeForm").bind('mousedown', window.modeForm.changeReplyAttr);
            jQuery("#replyList").bind('mousedown', window.modeForm.changeReplyAttr);
            jQuery(".wea-new-top-content").each(
                function () {
                    jQuery(this).scroll(function () {
                        window.modeForm.changeReplyAttr();
                    });
                }
            )

        }*/

        //加载css
        if (modeField && modeField.LayoutStyle) {
            jQuery("body").append(modeField.LayoutStyle);
        }
        let styles = modeField ? modeField.cssArr : [];
        for (let i = 0; i < styles.length; i++) {
            jQuery("body").append(styles[i]);
        }

        //加载布局js
        let scripts = modeField ? modeField.scripts : "";
        if (scripts) {
            script = document.createElement('script');
            script.id = "layoutScript0";
            script.innerHTML = scripts;
            document.body.appendChild(script);
        }
        let jsArr = modeField ? modeField.jsArr : null;
        if (jsArr) {
            for (let j = 0; j < jsArr.length; j++) {
                let jsSrc = jsArr[j];
                let srcJs = document.createElement('script');
                srcJs.type = "text/javascript";
                srcJs.id = "layoutScript" + j;
                srcJs.src = jsSrc;
                document.head.appendChild(srcJs);
            }
        }

        if (type == "0") {

        }

    }
}

/**
 * 表单必填内容校验
 */
export const check_form = (needcheck, mainFields, mainData, detailData) => {
    try {
        let nc = needcheck.split(",");
        for (let i = 0; i < nc.length; i++) {
            let id = nc[i];
            if (id != "") {
                let fieldid;
                if (id.indexOf("_") > 0) {
                    let ids = id.split("_");
                    fieldid = ids[0].substring(5);
                } else {
                    fieldid = id.substring(5);
                }
                let field = mainFields[fieldid];
                let fieldname = field.fieldlabel;
                if (field.detailtable && id.indexOf("_") < 0) {
                    let tablename = field.detailtable;
                    let size = detailData.data[tablename].data.length;
                    for (let j = 0; j < size; j++) {
                        //if (!jQuery("#" + id + "_" + j).val()) {
                        if (!detailData.data[tablename].data[j][fieldid].value) {
                            printMessage("warning", fieldname + " 未填写", "必填内容未填写");
                            //alert(fieldname + "未填写");
                            return false;
                        }
                    }
                } else {
                    //if (!jQuery("#" + id).val()) {
                    if (!mainData.data[fieldid].value) {
                        printMessage("warning", fieldname + " 未填写", "必填内容未填写");
                        //alert(fieldname + "未填写");
                        return false;
                    }
                }
            }
        }
    } catch (e) {
        writeLog("",e)
        return false;
    }
    return true;
}

/**
 * 提示信息
 */
export const printMessage = (type, message, title?: string) => {
    if (type == "warning") {
        Modal.warning({
            title: title,
            content: message,
            okText: "确认",
        });
    }
}


export const deepCopy = (obj) => {
    let newO = {};
    if (obj instanceof Array) {
        newO = [];
    }
    for (let key in obj) {
        let val = obj[key];
        newO[key] = typeof val === 'object' ? arguments.callee(val) : val;
    }
    return newO;
}

/**
 * contains方法 判断数组中是否包含某一元素
 */
export const contains = (arr, obj) => {
    if (!arr)
        return false;
    let i = arr.length;
    while (i--) {
        if (arr[i] === obj) {
            return true;
        }
    }
    return false;
}

export const writeLog = (msg,e) => {
    if(console&&console.log){
        console.log(msg, e);
    }
}


/**
 * 获取字段值方法
 */
export const getFieldValue = (fieldid, drowIndex) => {
    let card = window.cubeStore.Card;
    let mainFields = card.mainFields;
    let fieldObj = mainFields[fieldid];
    let detailtable = fieldObj.detailtable;
    if (!!fieldObj) {
        try {
            if (detailtable) {
                let detailData = card.detailData;
                return detailData.data[detailtable].data[drowIndex][fieldid].value;
            } else {
                let mainData = card.mainData;
                return mainData.data[fieldid].value;
            }
        } catch (e) {
            writeLog("输入内容有误！", e);
        }
    } else {
        writeLog("输入内容有误！","");
    }
    return "";
}
//--------------------------------------------------------------------------联动相关js start

export const getChangeData = (fieldObj, value, symbol, drowIndex, mainData, detailData) => {
    let flag = false;
    const fieldid = fieldObj.fieldid;
    const htmltype = fieldObj ? fieldObj.htmltype : "";
    const detailtype = fieldObj ? fieldObj.type : "";

    if (htmltype == "2" && detailtype == 2) {//没有id的组件也无法集成表单联动的字段  从统一封装到mainDara 的 otherData中
        let otherData = mainData.otherData ? mainData.otherData : {};
        if (symbol == "emaintable" || symbol.indexOf("mc_") == 0 || symbol.indexOf("tab_") == 0) {
            let _value = mainData.data[fieldid].value;
            if (_value !== value.replace(/^\s+|\s+$/gm, '')) {
                otherData["field" + fieldid] = value;
                flag = true;
            }
        } else {
            let _value = detailData.data[symbol].data[drowIndex][fieldid].value;
            if (_value !== value.replace(/^\s+|\s+$/gm, '')) {
                otherData["field" + fieldid + "_" + drowIndex] = value;
                flag = true;
            }
        }
        mainData.otherData = otherData;
    }
    try {
        let specialobj = fieldObj.specialobj;
        if (symbol == "emaintable" || symbol.indexOf("mc_") == 0 || symbol.indexOf("tab_") == 0) {//处理字段的值 value未改变直接return 不执行后续方法
            let _value = mainData.data[fieldid].value;
            if (htmltype == "2" && detailtype == 2) {
                if (_value.replace(/^\s+|\s+$/gm, '') !== value.replace(/^\s+|\s+$/gm, '')) {
                    flag = true;
                }
            } else {
                if (_value !== value) {
                    flag = true;
                }
            }
            mainData.data[fieldid].value = value;//修改Redux字段值 已经改为在actions changeFieldData中处理 这里执行设置value只是提供给后续的联动方法使用最新的value
            if (specialobj)
                mainData.data[fieldid].specialobj = specialobj;
        } else {
            let _value = detailData.data[symbol].data[drowIndex][fieldid].value;
            if (htmltype == "2" && detailtype == 2) {
                if (_value.replace(/^\s+|\s+$/gm, '') !== value.replace(/^\s+|\s+$/gm, '')) {
                    flag = true;
                }
            } else {
                if (_value !== value) {
                    flag = true;
                }
            }
            detailData.data[symbol].data[drowIndex][fieldid].value = value;//修改Redux字段值 已经改为在actions changeFieldData中处理 这里执行设置value只是提供给后续的联动方法使用最新的value
            if (specialobj)
                detailData.data[symbol].data[drowIndex][fieldid].specialobj = specialobj;
        }
    } catch (e) {
        alert(e);
    }
    return flag;
}


export const changeField = (changeData, _mainData, _detailData, _mainFields, page) => {
    let mainData = jQuery.extend(true, {}, _mainData);
    let detailData = jQuery.extend(true, {}, _detailData);
    let mainFields = jQuery.extend(true, {}, _mainFields);
    let triggrtData = {};//需要触发联动的字段集合
    let returnData = {
        data: {}, mainFields: changeData._mainFields ? changeData._mainFields : {}
    };
    for (let item in changeData.data) {//先循环value
        let obj = changeData.data[item];
        if (getChangeData(obj.fieldObj, obj.value, obj.symbol, obj.drowIndex, mainData, detailData)) {
            triggrtData[item] = obj;
            returnData.data[item] = obj;
        }
    }
    page.actions.changeFieldData(returnData);

    for (let item in triggrtData) {//再触发联动
        let obj = triggrtData[item];
        changeFieldLink(obj.fieldObj, obj.value, obj.symbol, obj.drowIndex, mainData, detailData, mainFields, page);
    }
}

/**
 * 所有联动方法 changeFiele中涉及到的所有字段赋值 都使用此方法执行并触发目标字段的所有联动方法
 * 已废弃  迁移到formaction fieldDataChange方法
 */
export const changeFieldLink = (fieldObj, value, symbol, drowIndex, _mainData, _detailData, _mainFields, page) => {
    let mainData = jQuery.extend(true, {}, _mainData);
    let detailData = jQuery.extend(true, {}, _detailData);
    let mainFields = jQuery.extend(true, {}, _mainFields);

    const modeField = page.modeField;
    const orderlyjson = page.orderlyjson;
    const detailTable = page.detailTable;

    let fieldid = fieldObj.fieldid;
    // const htmltype = fieldObj ? fieldObj.htmltype : "";
    // const detailtype = fieldObj ? fieldObj.type : "";

    let changeData = { data: {}, _mainFields: {}, _detailData: { data: {} } };
    //每种计算类型单独try catch 防止一种出错所有都无法执行
    try {
        let colcalstr = modeField.colcalstr;
        let colCons = colcalstr[fieldid];
        if (colCons) {//列字段规则
            changecolCons(symbol, mainData, colCons, detailData, fieldid, mainFields, changeData);
        }
    } catch (e) {
        writeLog("",e);
    }


    try {
        let rowcalstr = modeField.rowcalstr;
        let rowCons = rowcalstr[fieldid];
        if (rowCons) {//行字段规则
            changerowCons(symbol, mainData, rowCons, detailData, mainFields, modeField, drowIndex, changeData);
        }
    } catch (e) {
        writeLog("",e)
     }


    try {
        let formula = orderlyjson.formula;
        let forCons = formula[fieldid];
        if (forCons) {//excel中的公式
            changeformula(symbol, drowIndex, forCons, mainData, detailData, mainFields, orderlyjson.etables, fieldObj, page, changeData);
        }
    } catch (e) { writeLog("",e) }

    try {
        let inputentry = modeField.inputentry;//字段联动
        let inputCons = inputentry[fieldid];
        if (inputCons) {//字段联动
            //dataInput(value, symbol, drowIndex, inputCons, mainData, detailData, mainFields, orderlyjson.etables, fieldObj, detailTable, page);
            /*mainData = returnObj.mainData;
            detailData = returnObj.detailData;
            mainFields = returnObj.mainFields;*/
        }
    } catch (e) { writeLog("",e) }

    try {
        let fieldattr = modeField.fieldattr;//字段属性
        let fieldCons = fieldattr[fieldid];
        if (fieldCons) {//字段属性
            let returnObj = checkFieldAttr(value, symbol, drowIndex, fieldCons, mainData, detailData, mainFields, orderlyjson.etables, fieldObj, detailTable, page);
            mainData = returnObj.mainData;
            detailData = returnObj.detailData;
            mainFields = returnObj.mainFields;
        }
    } catch (e) { writeLog("",e) }


    if (fieldObj.htmltype == "5") {//如果是选择框字段
        //首先解析属性联动
        try {
            let linkage = modeField.linkage;
            let linkCons = linkage[fieldid];
            if (linkCons) {//字段属性
                let returnObj = checkShowAttr(value, symbol, drowIndex, linkCons, mainData, detailData, mainFields, fieldObj) as any;//属性联动
                mainData = returnObj.mainData;
                detailData = returnObj.detailData;
                mainFields = returnObj.mainFields;
            }
        } catch (e) { writeLog("",e) }

        //解析子项联动
        try {
            let returnObj = changeSelectItem(fieldObj, symbol, value, drowIndex, mainData, detailData, mainFields, page) as any;
            mainData = returnObj.mainData;
            detailData = returnObj.detailData;
            mainFields = returnObj.mainFields;
        } catch (e) { writeLog("",e) }
    }

    //触发bindPropertyChange
    try {
        let fieldName = symbol == "emaintable" ? `field${fieldid}` : `field${fieldid}_${drowIndex}`;
        if (fieldName in window.__propertyChangeFnArray) {
            window.__propertyChangeFnArray[fieldName].map(fn => {
                try {
                    fn(jQuery("#" + fieldName)[0]);
                } catch (e) { writeLog("",e) }
            });
        }
    } catch (e) { writeLog("",e) }
    return { mainData, detailData, mainFields }
}

/**
 * 单元格格式解析
 */
export const convertValue = (realval, formatJSON) => {
    try {
        let formatval = "";
        let numberType = parseInt(formatJSON["numberType"]);
        if (numberType === 1) {			//1常规
            return realval;
        } else if (numberType === 2) {	//2数值
            const transQfw = parseInt(formatJSON["thousands"] || 0) === 1;
            const transAbs = formatJSON["formatPattern"] == "3" || formatJSON["formatPattern"] == "4";
            if (parseInt(formatJSON["decimals"]) < 0) {
                return realval;
            }
            formatval = formatFloatValue(realval, parseInt(formatJSON["decimals"]), transQfw, transAbs);
        } else if (numberType === 3) {	//3日期
            //formatval = this.formatToDate(realval,formatJSON["formatPattern"]);
            formatval = WeaTools.formatDate(realval, formatJSON["formatPattern"]);
        } else if (numberType === 4) {	//4时间
            //formatval = this.formatToTime(realval,formatJSON["formatPattern"]);
            formatval = WeaTools.formatTime(realval, formatJSON["formatPattern"]);
        } else if (numberType === 5) {	//5百分比
            formatval = formatToPercent(realval, formatJSON["decimals"]);
        } else if (numberType === 6) {	//6科学计数
            formatval = formatToScience(realval, formatJSON["decimals"]);
        } else if (numberType === 7) {	//7文本
        } else if (numberType === 8) {	//8特殊
            formatval = formatToSpecial(realval, formatJSON["formatPattern"]);
        }
        return formatval;
    } catch (e) {
        writeLog("format error:",e)
        return realval;
    }
}

/**
 * 单元格格式-转百分比
 */
export const formatToPercent = (realVal, decimals) => {
    const pattern = new RegExp("^(-?\\d+)(\\.\\d+)?$");
    if (!pattern.test(realVal)) {
        return realVal;
    }
    return formatFloatValue(Number(realVal) * 100, parseInt(decimals), false) + "%";
}

/**
 * 单元格格式-转科学计数
 */
export const formatToScience = (realVal, decimals) => {
    const pattern = new RegExp("^(-?\\d+)(\\.\\d+)?$");
    if (!pattern.test(realVal)) {
        return realVal;
    }
    let result = Number(realVal).toExponential(decimals).toUpperCase();
    result = result.replace(/E(\+|-)(\d){1}$/, "E$10$2");	//补零
    return result;
}

/**
 * 单元格格式-特殊字符
 */
export const formatToSpecial = (realVal, formatPattern) => {
    const pattern = new RegExp("^(-?\\d{1,12})(\\.\\d+)?$");
    if (!pattern.test(realVal)) {
        return realVal;
    }
    if (parseInt(formatPattern) === 1) {
        const digit = ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        const unit = [["", "万", "亿"], ["", "十", "百", "千"]];
        return specialTrans(realVal, digit, unit);
    } else {
        const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
        const unit = [["", "万", "亿"], ["", "拾", "佰", "千"]];
        return specialTrans(realVal, digit, unit);
    }
}

export const specialTrans = (realVal, digit, unit) => {
    realVal = parseFloat(realVal).toString();
    if (parseFloat(realVal) === 0) {
        return digit[0];
    }
    let headfix = "";
    let intPar_t = "";
    let pointPar_t = "";

    if (parseFloat(realVal) < 0) {
        realVal = realVal.substring(1);
        headfix = "-";
    }
    let realValArr = realVal.split(".");
    let intPar = jQuery.trim(realValArr[0]);
    while (intPar.length > 0 && parseInt(intPar[0]) === 0) {
        intPar = intPar.substr(1);
    }
    let pointPar = realValArr.length === 2 ? jQuery.trim(realValArr[1]) : "";
    let lastflag = false;
    let intParArr = intPar.length > 0 ? intPar.toString().split('') : [];
    let pointParArr = pointPar.length > 0 ? pointPar.toString().split('') : [];
    let j = 0;

    pointPar_t = pointPar.length > 0 ? "." : pointPar_t;
    pointParArr.map(v => {
        pointPar_t = pointPar_t + digit[parseInt(v)];
    });

    for (let i = intParArr.length - 1; i >= 0; i-- , j++) {
        let v = parseInt(intParArr[i]);
        let m = j % 4;
        if (m === 0) {
            lastflag = false;
            intPar_t = unit[0][j / 4] + intPar_t;
        }

        if (v === 0) {
            if (lastflag && intPar_t[0] === digit[0]) {
                intPar_t = digit[v] + intPar_t;
            }
        } else {
            lastflag = true;
            intPar_t = digit[v] + unit[1][m] + intPar_t;
        }
    }
    intPar_t = jQuery.trim(intPar_t).length === 0 ? digit[0] : intPar_t;
    return headfix + intPar_t + pointPar_t;
}

export const judgeValueIsNumber = (val) => {
    if (val === null || typeof val === "undefined")
        return false;
    let reg = /^(-?\d+)(\.\d+)?$/;
    return reg.test(val.toString());
}

export const judgeValueIsNumber0 = (val) => {
    if (val === '' || val === null || typeof val === "undefined")
        return true;
    let reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/;///^(-?\d+)(\.)?(\d+)?$/;
    return reg.test(val.toString());
}
export const judgeValueIsInt = (val) => {
    if (val === '' || val === null || typeof val === "undefined")
    return true;
    return /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/.test(val) && val.indexOf('.') < 0;
}

export const checkNumberFieldLenth = (_val: string, length: number, qfws: string) => {
    const [first, last] = _val.split('.');
    if (first.length > length) {
        return false;
    }
    if (qfws && last && last.length > parseInt(qfws, 0)) {
        return false;
    }
    return true;
}
/**
 * 数值转换(精度、千分位)等
 * @param {String} realval   真实值
 * @param {int} decimals  精度
 * @param {Boolean} transQfw  是否千分位
 * @param {Boolean} transAbs  是否绝对值
 */
export const formatFloatValue = (realval, decimals, transQfw, transAbs?: boolean) => {
    if (!judgeValueIsNumber(realval))     //非数值直接返回原始值
        return realval;
    realval = realval.toString();
    let formatval;
    if (decimals === 0) {		//需取整
        formatval = Math.round(parseFloat(realval)).toString();
    } else {
        //let n = Math.pow(10, decimals);
        formatval = realval;//(Math.round(parseFloat(realval) * n) / n).toString();
        let pindex = formatval.indexOf(".");
        let pointLength = pindex > -1 ? formatval.substr(pindex + 1).length : 0;	//当前小数位数
        if (decimals > pointLength) {		//需补零
            if (pindex == -1)
                formatval += ".";
            for (let i = 0; i < decimals - pointLength; i++) {
                formatval += "0";
            }
        }
    }
    let index = formatval.indexOf(".");
    let intPar = index > -1 ? formatval.substring(0, index) : formatval;
    let pointPar = index > -1 ? formatval.substring(index) : "";
    //取绝对值
    if (transAbs === true) {		//取绝对值
        intPar = Math.abs(intPar).toString();
    }
    if (transQfw === true) {				//整数位format成千分位
        let reg1 = /(-?\d+)(\d{3})/;
        while (reg1.test(intPar)) {
            intPar = intPar.replace(reg1, "$1,$2");
        }
    }
    formatval = intPar + pointPar;
    return formatval;
}

/**
 * 计算列字段规则
 */
export const changecolCons = (symbol, mainData, colCons, detailData, fieldid, mainFields, changeData) => {
    if (mainData) { }
    let maincalstr = colCons.maincalstr;
    if (!maincalstr)
        return;
    let mf = maincalstr.split("=")[0].replace("mainfield_", "");
    let detailValue = detailData.data[symbol].data;
    let mainFieldObj = mainFields[mf];

    let fieldSumValue = 0;
    const detailtype = mainFieldObj ? mainFieldObj.type : "";
    for (let i = 0; i < detailValue.length; i++) {
        let fieldValue = detailValue[i][fieldid].value;
        if (fieldValue && !isNaN(fieldValue))
            fieldSumValue += parseFloat(fieldValue)
    }
    let decimals = 2;
    if (mainFieldObj && (detailtype == "1" || detailtype == "2"))
        decimals = 0;
    else if (mainFieldObj && (detailtype == "3" || detailtype == "5"))
        decimals = parseInt(mainFieldObj.qfws, 0);
    let thousands = detailtype == "5" ? 1 : 0;
    changeData.data[mf] = { fieldObj: mainFields[mf], value: FormatFloatValue(fieldSumValue, decimals, thousands), symbol: "emaintable" }
    //return changeField(mainFields[mf], FormatFloatValue(fieldSumValue, decimals, thousands), "emaintable", null, mainData, detailData, mainFields, page);
    //mainData.data[mf].value = FormatFloatValue(fieldSumValue, decimals, thousands);
    //return mainData;
}

/**
 * 计算行字段规则
 */
export const changerowCons = (symbol, mainData, rowCons, detailData, mainFields, modeField, drowIndex, changeData) => {
    //let colcalstr = modeField.colcalstr;
    if (modeField) { }
    for (let item in rowCons) {
        let cons = rowCons[item];
        let pat = new RegExp("detailfield_\\d+");
        let result;
        do {
            result = pat.exec(cons);
            let fvalue;
            if (result) {
                let fid = result[0].replace("detailfield_", "");
                let fidValue = detailData.data[symbol].data[drowIndex][fid].value;
                fvalue = (!fidValue || isNaN(fidValue)) ? "0" : parseFloat(fidValue);
                cons = cons.replace(result, fvalue);
            }
        } while (result != null);
        let changeValue = eval(cons);
        changeData.data[item + "_" + drowIndex] = { fieldObj: mainFields[item], value: changeValue, symbol, drowIndex }
    }
    return { mainData, detailData, mainFields };
}

/**
 * 行列规则补0方法
 */
export const FormatFloatValue = (realval, decimals, thousands) => {
    let regnum = /^(-?\d+)(\.\d+)?$/;
    if (!regnum.test(realval)) {
        return realval;
    }
    realval = realval.toString();
    let formatval;
    if (decimals === 0) {		//需取整
        formatval = Math.round(parseFloat(realval));
    } else {
        let n = Math.pow(10, decimals);
        formatval = Math.round(parseFloat(realval) * n) / n;
        let pindex = realval.indexOf(".");
        let pointLength = pindex > -1 ? realval.substr(pindex + 1).length : 0;	//当前小数位数
        if (decimals > pointLength) {		//需补零
            if (pindex == -1)
                formatval += ".";
            for (let i = 0; i < decimals - pointLength; i++) {
                formatval += "0";
            }
        }
    }
    formatval = formatval.toString();
    let index = formatval.indexOf(".");
    let intPar = index > -1 ? formatval.substring(0, index) : formatval;
    let pointPar = index > -1 ? formatval.substring(index) : "";
    if (thousands === 1) {				//整数位format成千分位
        let reg1 = /(-?\d+)(\d{3})/;
        while (reg1.test(intPar)) {
            intPar = intPar.replace(reg1, "$1,$2");
        }
    }
    formatval = intPar + pointPar;
    return formatval;
}

//---------------------------------------------------------------解析公式excel布局中的公式start

/**
 * excel布局公式计算
 * 新增dealType参数 表示当前操作状态 1字段变更 2页面刷新 3新增明细 4删除明细
 * 新增curTableName参数  作用在新增、删除明细行的时候 标识新增的行的表名 字段公式存在明细表赋值给主表的计算关系 执行逻辑如下
 * 删除行时候 只有赋值字段是主表字段 取值字段是这个明细的公式才执行
 * 添加行时候 赋值字段、取值字段只要有包含了这一明细的字段的都会执行
 */
export const changeformula = (symbol, drowIndex, forCons, mainData, detailData, mainFields, etables, TriggerFieldObj, changeData, dealType, curTableName?: any, _?: any) => {
    if (symbol) { }
    for (let item in forCons) {
        let formula = forCons[item];
        let destcell = formula.destcell;
        const fieldid = convertCellAttrToFieldid(etables, destcell);
        let formulaTxt = jQuery.trim(formula.formulatxt).substring(1);
        //let analysistxt = jQuery.trim(formula.analysistxt).substring(1);
        let cellrange = formula.cellrange;

        let conFlag = false;
        if (dealType == "3") {//添加明细
            conFlag = destcell.indexOf(curTableName.toUpperCase()) > -1 || formulaTxt.indexOf(curTableName.toUpperCase()) > -1;
            //赋值字段或者计算公式里 任意一个包含了这个明细的字段
        } else if (dealType == "4") {//删除明细
            conFlag = destcell.indexOf("MAIN") > -1 && formulaTxt.indexOf(curTableName.toUpperCase()) > -1;
            //赋值字段是主表 计算公式包含了这个明细的字段
        }
        if (conFlag)
            continue;

        try {
            let result;
            let flag = true;

            if (destcell.indexOf("DETAIL_") === -1) {		//赋值给主表字段
                if ((/DETAIL_\d+\./).test(formulaTxt)) {	//取值字段包含明细表字段
                    const reg = /^(EXCEL_AVERAGE|EXCEL_MIN|EXCEL_MAX)\((\s*(MAIN|TAB_\d+|DETAIL_\d+)\.[A-Z]+\d+\s*(\,)?)+\)$/;
                    if (reg.test(formulaTxt)) {			//求平均、最大、最小特殊处理(例：AVG(明细字段或主字段))
                        result = calculate_detail_special(mainData, detailData, formulaTxt, cellrange, etables, mainFields);
                    } else {
                        result = calculate_detail_sum(mainData, detailData, formulaTxt, cellrange, etables, mainFields);
                    }
                } else {									//取值字段全部为主表字段
                    result = calculate_single(mainData, detailData, formulaTxt, cellrange, etables, mainFields, "-1");
                }
            } else {                                        //赋值给明细表字段
                let detailtable = TriggerFieldObj.detailtable;
                if (formulaTxt.match(/(MAIN|TAB_\d+)\./g) && !detailtable) {//取值字段包含主表字段 并且触发字段为主字段 需计算对应明细所有行记录
                    let returnObj = calculate_detailAllRow(fieldid, mainData, detailData, formulaTxt, cellrange, etables, mainFields, changeData);
                    mainData = returnObj ? returnObj.mainData : mainData;
                    detailData = returnObj ? returnObj.detailData : detailData;
                    mainFields = returnObj ? returnObj.mainFields : mainFields;
                    flag = false;
                } else {//触发字段为明细字段 暂时只考虑当前表单的联动
                    let fieldObj = mainFields[fieldid];
                    let tablename = fieldObj.detailtable;
                    if (tablename == detailtable) {
                        result = calculate_single(mainData, detailData, formulaTxt, cellrange, etables, mainFields, drowIndex + "");
                    } else {
                        message.warning("公式计算出错，请联系管理员");
                        flag = false;
                    }

                }
            }
            if (flag) {
                let fieldObj = mainFields[fieldid];
                let tablename = fieldObj.detailtable;
                //let returnObj;
                if (tablename) {
                    changeData.data[fieldid + "_" + drowIndex] = { fieldObj: mainFields[fieldid], value: result, symbol: tablename, drowIndex }
                } else {
                    changeData.data[fieldid] = { fieldObj: mainFields[fieldid], value: result, symbol: "emaintable" }
                }
            }
        } catch (e) {
            message.warning("公式计算错误:" + e);
            writeLog("formula calculate error:",e)
        }
    }
    return { mainData, detailData, mainFields };
}

/**
 * 单条/单行公式计算
 */
const calculate_single = (mainData, detailData, formulaTxt, cellrange, etables, mainFields, drowIndex) => {
    let _formulaTxt = replaceFormula(mainData, detailData, cellrange, formulaTxt, drowIndex, etables, mainFields, true);
    return eval(_formulaTxt);
}

/**
 * 明细列求平均/最大赋值主字段，特殊公式处理
 */
const calculate_detail_special = (mainData, detailData, formulaTxt, cellrange, etables, mainFields) => {
    let _formulaTxt = replaceFormula(mainData, detailData, cellrange, formulaTxt, "all", etables, mainFields, true);
    return eval(_formulaTxt);
}

/**
 * 明细所有行公式计算--赋值字段为明细字段，触发字段为主表字段；明细表每条记录都需经过公式计算再赋值
 * 还需要在公式计算时对默认添加明细行的默认值进行赋值为只有主表字段联动的结果 提供给添加明细时赋默认值
 */
const calculate_detailAllRow = (destFieldid, mainData, detailData, formulaTxt, cellrange, etables, mainFields, changeData) => {
    let tablename = mainFields[destFieldid].detailtable;
    let rowIndex = detailData.data[tablename].data.length;
    for (let i = 0; i < rowIndex; i++) {
        try {
            let formulaTxt_clone = formulaTxt;
            formulaTxt_clone = replaceFormula(mainData, detailData, cellrange, formulaTxt, i + "", etables, mainFields, true);
            let calculateResult = eval(formulaTxt_clone);
            //detailData.data[tablename].data[i][destFieldid].value = calculateResult;
            changeData.data[destFieldid + "_" + i] = { fieldObj: mainFields[destFieldid], value: calculateResult, symbol: tablename, drowIndex: i }

            let dData = changeData._detailData.data[tablename] ? changeData._detailData.data[tablename] : {};
            let defaultValue = dData.defaultValue ? dData.defaultValue : {};
            defaultValue[destFieldid] = calculateResult;
            dData.defaultValue = defaultValue;
            changeData._detailData.data[tablename] = dData;
        } catch (e) { }
    }
    return { mainData, detailData, mainFields };
}

/**
 * 明细作为取值字段的公式，计算明细每一行公式结果，再合计赋值主字段(修复之前主字段明细字段合计错误问题、多个明细同时合计错误问题)
 */
const calculate_detail_sum = (mainData, detailData, formulaTxt, cellrange, etables, mainFields) => {
    let sumResult = 0;
    const reg = /(DETAIL_\d+)/g;
    let allRowIndex = 0;
    formulaTxt.match(reg).map(detail => {
        let detailMark = detail.toLowerCase();
        let curRowIndex = detailData.data[detailMark].data.length;
        if (curRowIndex > allRowIndex) {
            allRowIndex = curRowIndex;
        }
    });
    //此处的处理逻辑有bug  原有布局公式计算方式 cellrange中含有多个明细表的字段操作时 默认只用第一个明细表的rowindex做明细index数量
    //沿用部分原有计算逻辑，当含有多个明细时候 取明细行数量最多的子表的rowindex做循环  不存在的子表字段按照空值处理
    for (let i = 0; i < allRowIndex; i++) {
        try {
            let _formulaTxt = replaceFormula(mainData, detailData, cellrange, formulaTxt, i + "", etables, mainFields, i == 0);
            const singleRowResult = eval(_formulaTxt);
            if (!isNaN(parseFloat(singleRowResult))) {	//非法数值结果
                sumResult = rewrite_add(sumResult, singleRowResult);
            }
        } catch (ev) {
            message.warning("公式计算错误:" + ev);
            writeLog("公式计算错误:",ev)
        }
    }
    return sumResult;
}

/**
 * 替换公式，单元格标示替换成对应字段值
 */
const replaceFormula = (mainData, detailData, cellrange, formulatxt, rowid, etables, mainFields, flag) => {

    jQuery.each(cellrange, function (_, cellattr) {
        let cellValue = "";
        const fieldid = convertCellAttrToFieldid(etables, cellattr);
        if (rowid === "all" && cellattr.indexOf("DETAIL_") > -1) {	//需替换明细所有行字段
            //let groupid = getGroupid(cellattr);
            let fieldObj = mainFields[fieldid];
            let tablename = fieldObj.detailtable;
            for (let i = 0; i < detailData.data[tablename].data.length; i++) {
                let _cellValue = detailData.data[tablename].data[i][fieldid].value;
                _cellValue = _cellValue ? _cellValue : "\"emptyval\"";
                if (i != 0) _cellValue = "," + _cellValue;
                cellValue += _cellValue;
            }
        } else {
            let fieldObj = mainFields[fieldid];
            let tablename = fieldObj.detailtable;
            if (tablename) {
                try {
                    cellValue = detailData.data[tablename].data[rowid][fieldid].value;
                    cellValue = cellValue ? cellValue : "\"emptyval\"";
                } catch (e) {
                    cellValue = "\"emptyval\"";
                }
            } else {
                //cellValue = rowid=="0"?(mainData[fieldid].value?mainData[fieldid].value:"emptyval"):"emptyval";
                if (flag) {
                    cellValue = mainData.data[fieldid].value;
                    cellValue = cellValue ? cellValue : "\"emptyval\"";
                } else {
                    cellValue = "\"emptyval\"";
                }
            }
        }
        if (cellValue == "") cellValue = "\"" + cellValue + "\"";
        let curindex = -1;
        while (formulatxt.indexOf(cellattr) > curindex) {
            curindex = formulatxt.indexOf(cellattr);
            let str1 = formulatxt.substring(0, curindex);
            let str2 = formulatxt.substring(curindex + cellattr.length);
            let reg = /^[0-9]$/;
            let nextchar = str2.substr(0, 1);
            if (reg.test(nextchar)) continue;
            formulatxt = str1 + cellValue + str2;
        }
    });

    return formulatxt;
}

/**
 * 公式标示转换成单元格标示(例：DETAIL_1.C4------>detail_1_4_3)
 */
const convertCellAttrToFieldid = (etables, cellAttr) => {
    const fa = cellAttr.split("\.");
    const symbol = fa[0] == "MAIN" ? "emaintable" : fa[0].toLowerCase();
    const tObj = etables[symbol];
    const letter = fa[1];
    const rowid = parseInt(letter.match(/\d+$/)[0]) - 1;
    const colid = convertCharToInt(letter.match(/^[a-zA-Z]+/)[0]) - 1;
    let id = rowid + "," + colid;
    let fieldObj = tObj[id];
    return fieldObj.field;
}

/**
 * 字母转数字
 */
const convertCharToInt = (value) => {
    let rtn = 0;
    let powIndex = 0;
    for (let i = value.length - 1; i >= 0; i--) {
        let tmpInt = value[i].charCodeAt() - 64;
        rtn += Math.pow(26, powIndex) * tmpInt;
        powIndex++;
    }
    return rtn;
}

/**
 * 获取属于哪个明细表groupid
 */
export const getGroupid = (cellattr) => {
    let idx = cellattr.indexOf("DETAIL_");
    if (cellattr.indexOf("DETAIL_") == -1)
        return -1;
    let groupid = cellattr.substring(idx + 7, cellattr.indexOf("."));
    return parseInt(groupid) - 1;
}

/**
 * JS parseFloat求和精度不一致问题解决
 */
function rewrite_add(arg1, arg2) {
    let r1 = 0, r2 = 0;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) { }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) { }
    let m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

/**
 * 求和
 */
export function EXCEL_SUM() {
    let result = 0;
    for (let i = 0; i < arguments.length; i++) {
        let par = arguments[i];
        if (!isNaN(parseFloat(par))) {
            result = rewrite_add(result, par);
        }
    }
    return result;
}

/**
 * 求平均数
 */
export function EXCEL_AVERAGE() {
    let count = 0;
    let sumVal = 0;
    for (let i = 0; i < arguments.length; i++) {
        let par = arguments[i];
        if (!isNaN(parseFloat(par))) {
            //sumVal += parseFloat(par);
            sumVal = rewrite_add(sumVal, par);
            count++;
        }
    }
    if (count > 0) {
        return sumVal / count;
    } else {
        throw new Error("EXCEL_AVERAGE divisor is zero");
    }
}

/**
 * 求绝对值
 */
export function EXCEL_ABS() {
    if (arguments.length == 1) {
        let par = arguments[0];
        if (!isNaN(parseFloat(par))) {
            let result = Math.abs(parseFloat(par));
            return result;
        } else {
            throw new Error("EXCEL_ABS arguments value is not a number");
        }
    } else {
        throw new Error("EXCEL_ABS arguments number must equal one");
    }
}

/**
 * 精度计算
 */
export function EXCEL_ROUND() {
    if (arguments.length == 2) {
        let result = 0;
        let par1 = arguments[0];
        let par2 = arguments[1];
        if (!isNaN(parseFloat(par1))) {
            par1 = parseFloat(par1);
        } else {
            throw new Error("EXCEL_ROUND first argument value is not a number");
        }
        if (par2) {
            par2 = parseInt(par2);
        } else {
            throw new Error("EXCEL_ROUND second argument value is not a int");
        }
        result = par1.toFixed(par2);
        return result;
    } else {
        throw new Error("EXCEL_ROUND arguments number must equal two");
    }
}

/**
 * 条件判断
 */
export function EXCEL_IF() {
    if (arguments.length == 3) {
        if (eval(arguments[0])) {
            return arguments[1];
        } else {
            return arguments[2];
        }
    } else {
        throw new Error("EXCEL_IF arguments number must equal three");
    }
}

/**
 * 求最大值
 */
export function EXCEL_MAX() {
    let result;
    for (let i = 0; i < arguments.length; i++) {
        let par = arguments[i];
        if (!isNaN(parseFloat(par))) {
            if (result == null) {
                result = parseFloat(par);
            } else {
                if (parseFloat(par) > result)
                    result = parseFloat(par);
            }
        }
    }
    if (result != null) {
        return result;
    } else {
        throw new Error("EXCEL_MAX arguments value must contain a number");
    }
}

/**
 * 求最小值
 */
export function EXCEL_MIN() {
    let result;
    for (let i = 0; i < arguments.length; i++) {
        let par = arguments[i];
        if (!isNaN(parseFloat(par))) {
            if (result == null) {
                result = parseFloat(par);
            } else {
                if (parseFloat(par) < result)
                    result = parseFloat(par);
            }
        }
    }
    if (result != null) {
        return result;
    } else {
        throw new Error("EXCEL_MIN arguments value must contain a number");
    }
}

//---------------------------------------------------------------解析公式excel布局中的公式end

/**
 * 解析字段联动
 */
export const dataInput0 = (value, symbol, drowIndex, inputCons, mainData, detailData, mainFields, etables, fieldObj, detailTable, page) => {
    if (etables || fieldObj) { }
    let dataInputArr = {};
    for (let i = 0; i < inputCons.length; i++) {
        let dataInputObj = inputCons[i];
        let id = dataInputObj.id;
        jQuery.ajax({
            url: "/api/formmode/card/dataInput",
            data: { formId: page.formId, value, id, data: symbol == "emaintable" ? JSON.stringify(mainData.data) : JSON.stringify(detailData.data[symbol].data[drowIndex]) },
            dataType: 'json',
            type: 'POST',
            async: false,
            success: function (res) {
                let data = res.data;
                for (let item in data) {
                    let dataObj = data[item];
                    if (item == "emaintable") {//主表字段联动结果是主表的
                        for (let field in dataObj) {
                            let valueObj = dataObj[field];
                            let fieldValue = valueObj.value;
                            let _fieldObj = mainFields[field];
                            if (valueObj.specialobj) {
                                _fieldObj.specialobj = valueObj.specialobj;
                            }
                            dataInputArr[field] = { fieldObj: _fieldObj, value: fieldValue, symbol: "emaintable" }
                            /*returnObj = changeField(_fieldObj, fieldValue, "emaintable", null, mainData, detailData, mainFields, page);
                            mainData = returnObj.mainData;
                            detailData = returnObj.detailData;
                            mainFields = returnObj.mainFields;*/
                            //mainData.data[field].value = value;//主表字段赋值
                        }
                    } else if (item == "detailData") {//明细表自身联动
                        for (let field in dataObj) {
                            let valueObj = dataObj[field];
                            let fieldValue = valueObj.value;
                            let _fieldObj = mainFields[field];
                            if (valueObj.specialobj) {
                                _fieldObj.specialobj = valueObj.specialobj;
                            }
                            dataInputArr[field + "_" + drowIndex] = { fieldObj: _fieldObj, value: fieldValue, symbol, drowIndex }
                            /*returnObj = changeField(_fieldObj, fieldValue, symbol, drowIndex, mainData, detailData, mainFields, page);
                            mainData = returnObj.mainData;
                            detailData = returnObj.detailData;
                            mainFields = returnObj.mainFields;*/
                        }
                    } else {//主表字段联动结果是明细的
                        let rowCount = detailData.data[item].data.length;
                        let i = 0;
                        for (; i < dataObj.length; i++) {
                            let rowObj = dataObj[i];
                            let addObj = JSON.parse(detailTable[item].addObj);
                            let key = (rowCount + i) + "";
                            addObj.index = key;
                            detailData.data[item].data.push(addObj);//子表方式修改，先加行 再赋值，触发联动事件
                            for (let field in rowObj) {
                                let valueObj = rowObj[field];
                                let fieldValue = valueObj.value;
                                let _fieldObj = mainFields[field];
                                if (valueObj.specialobj) {
                                    _fieldObj.specialobj = valueObj.specialobj;
                                }
                                //addObj[field].value = value;
                                //dataInputArr[field + "_" + (rowCount + i)] = { fieldObj: _fieldObj, value: fieldValue, symbol: item, drowIndex }//主表联动明细 直接触发
                                let returnObj = changeField(_fieldObj, fieldValue, item, rowCount + i, mainData, ) as any;
                                mainData = returnObj.mainData;
                                detailData = returnObj.detailData;
                                mainFields = returnObj.mainFields;
                            }
                        }
                        detailData.data[item].size = (parseInt(rowCount) + i);
                        let drs = detailData.detailRowSize;
                        detailData.detailRowSize = (parseInt(drs) + 1);
                    }
                }

            }
        })
    }
    for (let item in dataInputArr) {
        let obj = dataInputArr[item];
        let fieldObj = obj.fieldObj;
        let value = obj.value;
        let symbol = obj.symbol;
        let drowIndex = obj.drowIndex;
        let returnObj = changeField(fieldObj, value, symbol, drowIndex, mainData) as any;
        mainData = returnObj.mainData;
        detailData = returnObj.detailData;
        mainFields = returnObj.mainFields;
    }
    return { mainData, detailData, mainFields }
}

//export const dataInput = (value, symbol, drowIndex, inputCons, mainData, detailData, mainFields, etables, fieldObj, detailTable, page) => {
/*  for (let i = 0; i < inputCons.length; i++) {
     let changeData = { data: {}, _mainFields: {}, _detailData: { data: {} } };
     let dataInputObj = inputCons[i];
     let id = dataInputObj.id;
 } */
//return { mainData, detailData, mainFields }
//}

/**
 * 解析字段属性
 */
export const checkFieldAttr = (value, symbol, drowIndex, fieldCons, mainData, detailData, mainFields, etables, fieldObj, detailTable, page, changeData?: any) => {
    for (let item in fieldCons) {
        let obj = fieldCons[item];
        let field = mainFields[item];
        let valueObj;
        let fieldType = 0;
        let detailtable = field.detailtable;
        if (detailtable) {//联动字段为明细表
            let data = symbol == "emaintable" ? detailData.data[field.detailtable] : detailData.data[field.detailtable].data[drowIndex];
            fieldType = symbol == "emaintable" ? 2 : 1;
            valueObj = { ...mainData.data, ...data };
        } else {
            valueObj = mainData.data;
        }
        if (valueObj || fieldType || value || etables || fieldObj || detailTable || page) { }

        // let id = obj.id;
        let caltype = obj.caltype;
        // let htmltype = field ? field.htmltype : "";
        // let detailtype = field ? field.type : "";
        if (caltype == "2") {//字段赋值目前只支持主表字段（原有规则）
            let attrcontent = obj.attrcontent;
            let index = attrcontent.indexOf("doFieldMath(\"");
            if (index > -1) {
                attrcontent = attrcontent.substring(index + 13);
                index = attrcontent.lastIndexOf("\")");
                if (index > -1) {
                    attrcontent = attrcontent.substring(0, index);
                }
                const reg = /\$\d+\$/g;
                attrcontent.match(reg).map(detail => {
                    let fid = detail.replace(/\$/g, "");
                    let value = mainData.data[fid].value;
                    if (isNaN(parseFloat(value))) {
                        value = "0";
                    }
                    attrcontent = attrcontent.replace(detail, value);
                });
                let fieldValue;
                try {
                    fieldValue = eval(attrcontent);
                } catch (e) { }
                changeData.data[item] = { fieldObj: field, value: fieldValue, symbol: "emaintable" }
                /*let returnObj = changeField(field, fieldValue, "emaintable", null, mainData, detailData, mainFields, page);
                mainData = returnObj.mainData;
                detailData = returnObj.detailData;
                mainFields = returnObj.mainFields;*/
            }
        } else if (caltype == "5") {//地图元素不在联动中解析 使用ModeMap组件实现

        } else {
            //采用同步调用ajax防止多次dispatch造成参数之间相互影响
            /*jQuery.ajax({
                url: "/api/formmode/card/fieldAttr",
                data: { id, fieldType, fields: JSON.stringify(mainFields), data: JSON.stringify(valueObj), field: JSON.stringify(field) },
                dataType: 'json',
                type: 'POST',
                async: false,
                success: function (res) {*/

            /*API.fieldAttr({ id, fieldType, fields: JSON.stringify(mainFields), data: JSON.stringify(valueObj), field: JSON.stringify(field) }).then(({ data, api_errormsg, api_status }) => {
                if (api_status) {
                    let name;
                    let key;
                    if (fieldType != "2") {
                        if (data.length > 0) {
                            name = data[0].name;
                            key = data[0].key;
                        }
                    }
                    if (htmltype == "3") {//浏览框字段单独处理
                        if (detailtable && symbol == "emaintable") {
                            let size = data.length;

                            let specialobj = {
                                showname: "",
                                replaceDatas: new Array()
                            }

                            for (let j = 0; j < size; j++) {
                                name = data[j].name;
                                key = data[j].key;

                                let keys = key.split(",");
                                let names = name.replace(/&nbsp;/g, ",").split(",");
                                let replaceDatas = new Array();
                                let showname = "";
                                for (let i = 0; i < keys.length; i++) {
                                    showname += "," + names[i];
                                    replaceDatas.push({ id: keys[i], name: names[i] })
                                }
                                if (showname)
                                    showname = showname.substring(1);
                                specialobj.showname = showname;
                                specialobj.replaceDatas = replaceDatas;
                                field.specialobj = specialobj;
                            }
                            let returnObj = changeField(field, keys, detailtable, j, mainData, detailData, mainFields, page);
                            mainData = returnObj.mainData;
                            detailData = returnObj.detailData;
                            mainFields = returnObj.mainFields;
                        } else {
                            if (name) {
                                let keys = key.split(",");
                                let names = name.replace(/&nbsp;/g, ",").split(",");
                                let replaceDatas = new Array();
                                let showname = "";
                                for (let i = 0; i < keys.length; i++) {
                                    showname += "," + names[i];
                                    replaceDatas.push({ id: keys[i], name: names[i] })
                                }
                                if (showname)
                                    showname = showname.substring(1);
                                let specialobj = {
                                    showname: showname,
                                    replaceDatas: replaceDatas
                                }
                                field.specialobj = specialobj;
                                if (detailtable) {//当赋值字段是明细表字段时候 需要先判断是从主表字段的联动还是从明细字段的联动（实际设置中 只有sql字段支持这种配置 日期计算明细表关联主表字段）
                                    if (symbol != "emaintable") {//联动字段是明细时 只修改当前行的字段值
                                        let returnObj = changeField(field, keys, detailtable, drowIndex, mainData, detailData, mainFields, page);
                                        mainData = returnObj.mainData;
                                        detailData = returnObj.detailData;
                                        mainFields = returnObj.mainFields;
                                    }
                                } else {
                                    let returnObj = changeField(field, keys, "emaintable", null, mainData, detailData, mainFields, page);
                                    mainData = returnObj.mainData;
                                    detailData = returnObj.detailData;
                                    mainFields = returnObj.mainFields;
                                }
                            }
                        }
                    } else {//选择框字段跟其他字段一起处理 区别是选择框需要传key 而文本字段传name
                        if (detailtable) {//当赋值字段是明细表字段时候 需要先判断是从主表字段的联动还是从明细字段的联动
                            if (symbol == "emaintable") {//联动字段是主表时 修改所有明细对应字段
                                let size = data.length;
                                for (let j = 0; j < size; j++) {
                                    name = data[j].name;
                                    key = data[j].key;
                                    let returnObj = changeField(field, htmltype == "5" ? key : name, detailtable, j, mainData, detailData, mainFields, page);
                                    mainData = returnObj.mainData;
                                    detailData = returnObj.detailData;
                                    mainFields = returnObj.mainFields;
                                }
                            } else {//联动字段是明细时 只修改当前行的字段值
                                let returnObj = changeField(field, htmltype == "5" ? key : name, detailtable, drowIndex, mainData, detailData, mainFields, page);
                                mainData = returnObj.mainData;
                                detailData = returnObj.detailData;
                                mainFields = returnObj.mainFields;
                            }
                        } else {
                            let returnObj = changeField(field, htmltype == "5" ? key : name, "emaintable", null, mainData, detailData, mainFields, page);
                            mainData = returnObj.mainData;
                            detailData = returnObj.detailData;
                            mainFields = returnObj.mainFields;
                        }
                    }
                    page.actions.changeField({ mainData, detailData, mainFields });
                    //page.forceUpdate();//强制重新渲染
                }
            });*/
        }
    }
    return { mainData, detailData, mainFields }
}


export const checkshowAttrObj = (showAttrObj) => {
    return showAttrObj;
}

/**
 * 属性联动方法 属性联动中设置的参数 attrEdit，attrHide，attrView，attrMandatory 优先级高于 mainFields中默认的显示参数 isedit等
 */
export const checkShowAttr = (value, symbol, drowIndex, linkCons, mainData, detailData, mainFields, fieldObj, changeData?: any, _?: any) => {
    if (symbol || mainData || detailData) {

    }
    if (fieldObj.detailtable) {
        for (let index = 0; index < linkCons.length; index++) {
            let valueLinkage = linkCons[index];
            let selectfieldvalue = valueLinkage.selectfieldvalue;
            let tablename = fieldObj.detailtable;
            let viewattr = "";
            let changefieldids = valueLinkage.changefieldids;
            if (value == selectfieldvalue) {//对应到当前选中值得项目才加载属性联动样式 其余字段全部还原为空
                viewattr = valueLinkage ? valueLinkage.viewattr : "";
            }
            let cfa = changefieldids.split(",");
            let dData = changeData._detailData.data[tablename] ? changeData._detailData.data[tablename] : {};
            let dataArr = dData.data ? dData.data : {};
            let datas = dataArr[drowIndex] ? dataArr[drowIndex] : {};
            for (let i = 0; i < cfa.length; i++) {
                let cfid = cfa[i];
                let showAttrObj = jQuery.extend(true, {}, datas[cfid] ? datas[cfid] : { needBreak: false });
                if (showAttrObj.needBreak) {
                    continue;
                }
                showAttrObj.attrEdit = (viewattr == "") ? mainFields[cfid].isedit : ((viewattr == "3" || viewattr == "4") ? "0" : "1");
                showAttrObj.attrHide = (viewattr == "") ? mainFields[cfid].ishide : (viewattr == "4" ? "1" : "0");
                showAttrObj.attrView = (viewattr == "") ? mainFields[cfid].isview : (viewattr == "4" ? "0" : "1");
                //let mandatory = mainFields[cfid].attrMandatory;
                // let _mandatory = (viewattr == "") ? mainFields[cfid].ismandatory : (viewattr == "2" ? "1" : "0");
                showAttrObj.attrMandatory = (viewattr == "") ? mainFields[cfid].ismandatory : (viewattr == "2" ? "1" : "0");
                showAttrObj.needBreak = value == selectfieldvalue;
                datas[cfid] = showAttrObj;
            }
            dataArr[drowIndex] = datas;
            dData.data = dataArr;
            changeData._detailData.data[tablename] = dData;
        }
    } else {
        for (let index = 0; index < linkCons.length; index++) {
            let valueLinkage = linkCons[index];
            let selectfieldvalue = valueLinkage.selectfieldvalue;
            let viewattr = "";
            let changefieldids = valueLinkage.changefieldids;
            if (value == selectfieldvalue) {//对应到当前选中值得项目才加载属性联动样式 其余字段全部还原为空
                viewattr = valueLinkage ? valueLinkage.viewattr : "";
            }
            let cfa = changefieldids.split(",");
            if (cfa.length > 0) {
                for (let i = cfa.length - 1; i >= 0; i--) {
                    let cfid = cfa[i];
                    let showAttrObj = jQuery.extend(true, {}, changeData._mainFields[cfid] ? changeData._mainFields[cfid] : {});
                    if (showAttrObj.needBreak) {
                        continue;
                    }
                    showAttrObj.attrEdit = (viewattr == "") ? mainFields[cfid].isedit : ((viewattr == "3" || viewattr == "4") ? "0" : "1");
                    showAttrObj.attrHide = (viewattr == "") ? mainFields[cfid].ishide : (viewattr == "4" ? "1" : "0");
                    showAttrObj.attrView = (viewattr == "") ? mainFields[cfid].isview : (viewattr == "4" ? "0" : "1");
                    // let mandatory = mainFields[cfid].attrMandatory;
                    // let _mandatory = (viewattr == "") ? mainFields[cfid].ismandatory : (viewattr == "2" ? "1" : "0");
                    showAttrObj.attrMandatory = (viewattr == "") ? mainFields[cfid].ismandatory : (viewattr == "2" ? "1" : "0");
                    showAttrObj.needBreak = value == selectfieldvalue;
                    changeData._mainFields[cfid] = showAttrObj;
                }
            }
        }
    }
}


/**
 * 选择框子项联动
 */
export const changeSelectItem = (fieldObj, symbol, value, drowIndex, mainData, detailData, mainFields, changeData) => {
    let selectAttr = fieldObj ? fieldObj.selectAttr : {};
    let childfieldid = selectAttr.childfieldid ? selectAttr.childfieldid : 0;
    if (childfieldid != 0) {
        if (symbol == "emaintable") {
            let showAttrObj = changeData._mainFields[childfieldid] ? changeData._mainFields[childfieldid] : {};
            showAttrObj.pValue = value;
            changeData._mainFields[childfieldid] = showAttrObj;
            let cvalue = mainData.data[childfieldid].value;
            /*if (!contains(mainFields[childfieldid + ""].valueObj[value], cvalue)) {//如果子项当前值 不在联动出来的结果集中 则清空子项当前选中内容
                changeData.data[childfieldid] = { fieldObj: mainFields[childfieldid + ""], value: "", symbol: "emaintable" }
                /*let returnObj = changeField(mainFields[childfieldid + ""], "", "emaintable", null, mainData, detailData, mainFields, page);
                mainData = returnObj ? returnObj.mainData : mainData;
                detailData = returnObj ? returnObj.detailData : detailData;
                mainFields = returnObj ? returnObj.mainFields : mainFields;*/
            //mainData.data[childfieldid].value = "";
            //}
            let sValue = "";
            if (contains(mainFields[childfieldid + ""].valueObj[value], cvalue)) {
                sValue = cvalue;
            } else {
                let selectList = (mainFields[childfieldid + ""].selectAttr ? mainFields[childfieldid + ""].selectAttr : { selectList: [] }).selectList;
                for (let i = 0; i < selectList.length; i++) {
                    let selectvalue = selectList[i].selectvalue;
                    let isdefault = selectList[i].isdefault;
                    if (contains(mainFields[childfieldid + ""].valueObj[value], selectvalue + "") && isdefault === 1) {
                        sValue = selectvalue + "";
                        break;
                    }
                }
            }
            changeData.data[childfieldid] = { fieldObj: mainFields[childfieldid + ""], value: sValue, symbol: "emaintable" };
        } else {
            let dData = changeData._detailData.data[symbol] ? changeData._detailData.data[symbol] : {};
            let dataArr = dData.data ? dData.data : {};
            let datas = dataArr[drowIndex] ? dataArr[drowIndex] : {};
            let showAttrObj = datas[childfieldid] ? datas[childfieldid] : {};
            showAttrObj.pValue = value;
            datas[childfieldid] = showAttrObj;
            dataArr[drowIndex] = datas;
            dData.data = dataArr;
            changeData._detailData.data[symbol] = dData;
            //detailData.data[symbol].data[drowIndex][childfieldid].pValue = value;
            let cvalue = detailData.data[symbol].data[drowIndex][childfieldid].value;
            let sValue = "";
            if (contains(mainFields[childfieldid + ""].valueObj[value], cvalue)) {
                sValue = cvalue;
            } else {
                let selectList = (mainFields[childfieldid + ""].selectAttr ? mainFields[childfieldid + ""].selectAttr : { selectList: [] }).selectList;
                for (let i = 0; i < selectList.length; i++) {
                    let selectvalue = selectList[i].selectvalue;
                    let isdefault = selectList[i].isdefault;
                    if (contains(mainFields[childfieldid + ""].valueObj[value], selectvalue + "") && isdefault === 1) {
                        sValue = selectvalue + "";
                        break;
                    }
                }
            }

            changeData.data[childfieldid + "_" + drowIndex] = { fieldObj: mainFields[childfieldid + ""], value: sValue, symbol, drowIndex }
            /*if (!contains(mainFields[childfieldid + ""].valueObj[value], cvalue)) {
                changeData.data[childfieldid + "_" + drowIndex] = { fieldObj: mainFields[childfieldid + ""], value: "", symbol, drowIndex }
                /*let returnObj = changeField(mainFields[childfieldid + ""], "", symbol, drowIndex, mainData, detailData, mainFields, page);
                mainData = returnObj ? returnObj.mainData : mainData;
                detailData = returnObj ? returnObj.detailData : detailData;
                mainFields = returnObj ? returnObj.mainFields : mainFields;*/
            //detailData.data[symbol].data[drowIndex][childfieldid].value = "";
            //}
        }
    }
}


//--------------------------------------------------------------------------联动相关js end

/***************************字段校验相关js******************************* */

/**
 * 字段校验方法总入口 change校验
 */
export const checkField = (value, fieldObj) => {
    const fieldlabel = fieldObj ? fieldObj.fieldlabel : "";
    const detailtype = fieldObj ? fieldObj.type : "";
    const fielddbtype = fieldObj ? fieldObj.fielddbtype : "";
    if (detailtype == "1") {//文本类型字段
        if (fielddbtype.indexOf("varchar") > -1) {
            let fieldlength_tmp = parseInt(fielddbtype.substring(fielddbtype.indexOf("(") + 1, fielddbtype.length - 1));
            value = checkLength(value, fieldlength_tmp, fieldlabel);
        }
    } else if (detailtype == "2") {//整数类型字段
        value = checkcount(value);
        value = checkItemScale(value, "整数长度不能超过9位，请重新输入", -999999999, 999999999);
    } else if (detailtype == "3") {
        value = checkFloatLength(value);
    }
    return value;
}

/**
 * 字段校验方法总入口 blur校验
 */
export const checkFieldBlur = (value, fieldObj) => {
    const detailtype = fieldObj ? fieldObj.type : "";
    const qfws = fieldObj ? fieldObj.qfws : "2";

    let data = { value } as any;
    if (detailtype == "3") {
        value = checkFloat(value, parseInt(qfws));
        data.value = value;
        data.reload = true;
    } else if (detailtype == "5") {
        value = changeToThousands2(value, qfws, detailtype);
        data.value = value;
        data.reload = true;
    }

    return data;
}

/**
 * 字段校验方法总入口 focus校验
 */
export const checkFieldFocus = (value, fieldObj) => {
    const detailtype = fieldObj ? fieldObj.type : "";

    let data = { value } as any;
    if (detailtype == "5") {
        value = changeToNormalFormat(value);
        data.value = value;
        data.reload = true;
    }

    return data;
}

/**
 * 字段长度校验
 */
export const checkLength = (value, len, fieldlabel) => {
    if (len != 0 && realLength(value) > len) {
        printMessage("warning", fieldlabel + "文本长度不能超过" + len + ",(1个中文字符等于3个长度)");
        while (realLength(value) > len) {
            value = value.substring(0, value.length - 1);
        }
    }
    return value;
}

export const checkFloatLength = (value) => {
    return value;
}


export const realLengthInput = (str) => {
    let j = 0;
    for (let i = 0; i <= str.length - 1; i++) {
        j = j + 1;
        if ((str.charCodeAt(i)) > 127) {
            j = j + 2;
        }
    }
    return j;
}

export const checkLengthInput = (str, strLen, elMaxLen) => {
    if (strLen <= elMaxLen) {
        return str;
    }

    let j = 0;
    for (let i = 0; i <= str.length - 1; i++) {
        j = j + 1;
        if ((str.charCodeAt(i)) > 127) {
            j = j + 2;
        }

        if (j > elMaxLen) {
            return str.substring(0, i);
        }

        if (j == elMaxLen) {
            return str.substring(0, i + 1);
        }
    }
    return str;
}
/**
 * 数字校验
 */
export const checkcount = (value) => {
    let valuechar = value.split("");
    let isnumber = false;
    for (let i = 0; i < valuechar.length; i++) {
        let charnumber = parseInt(valuechar[i]);
        if (isNaN(charnumber) && (valuechar[i] != "-" || (valuechar[i] == "-" && i != 0))) {
            isnumber = true;
        }
        if (valuechar.length == 1 && valuechar[i] == "-") {
            isnumber = true;
        }
    }
    return isnumber ? "" : value;
}

/**
 * 数字范围校验
 */
export const checkItemScale = (value, msg, minValue, maxValue) => {
    let val = value;
    if (val != "") {
        try {
            //调用parseInt转换类型必须指定第二个参数值，来设置保存数字的进制的值。否则有可能使用8进制 16进制来转换数据。
            val = parseInt(val, 10);
            if (val < minValue || val > maxValue) {
                printMessage("warning", msg);
                return "";
            } else {
                return value;
            }
        } catch (e) {
            return "";
        }
    }
    return value;
}

/**
 * 金额前分位置获取焦点时候去掉,
 */
export const changeToNormalFormat = (value) => {
    return value.replace(/,/g, "");
}

/**
 * 千分位转换
 */
export const changeToThousands2 = (sourcevalue, dlength, detailtype) => {
    let tovalue;
    if (0 < dlength && detailtype != "4" && detailtype != "5") {
        sourcevalue = addZero(sourcevalue, dlength);
        tovalue = sourcevalue;
    } else if (detailtype == "4" || detailtype == "5") {
        sourcevalue = addZero(sourcevalue, dlength);
        sourcevalue = sourcevalue.replace(/\s+/g, "");
        let sourcevalue01 = sourcevalue;
        if (sourcevalue01 != '') {
            tovalue = commafy(sourcevalue01);
        } else {
            tovalue = sourcevalue;
        }
    } else {
        tovalue = sourcevalue;
    }
    return tovalue;
}

/**
 * 数字格式转换成千分位
 */
export const commafy = (num) => {
    num = num + "";
    num = num.replace(/[ ]/g, ""); //去除空格
    if (num == "") {
        return;
    }
    if (isNaN(num)) {
        return;
    }
    //2.针对是否有小数点，分情况处理
    let index = num.indexOf(".");
    if (index == -1) {//无小数点
        let reg = /(-?\d+)(\d{3})/;
        while (reg.test(num)) {
            num = num.replace(reg, "$1,$2");
        }
    } else {
        let intPart = num.substring(0, index);
        let pointPart = num.substring(index + 1, num.length);
        let reg = /(-?\d+)(\d{3})/;
        while (reg.test(intPart)) {
            intPart = intPart.replace(reg, "$1,$2");
        }
        num = intPart + "." + pointPart;
    }
    return num;
}


/**
 * 浮点数校验
 */
export const checkFloat = (value, qfws) => {
    //let reg = /^-?([1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0)$/;
    let reg = /^(-?\d+)(\.\d+)?$/;
    if (value != "") {
        if (!reg.test(value)) {
            return "";
        } else {
            return addZero(value, qfws);
        }
    }
    return value;
}

/**
 * 补充0方法
 */
export const addZero = (aNumber, precision) => {
    if (!precision) {
        return aNumber;
    }
    if (aNumber == null || aNumber.toString().trim() == "" || isNaN(aNumber)) return "";
    let valInt = (aNumber.toString().split(".")[1] + "").length;
    if (valInt != precision) {
        let lengInt = precision - valInt;
        //判断添加小数位0的个数
        if (lengInt == 1) {
            aNumber += "0";
        } else if (lengInt == 2) {
            aNumber += "00";
        } else if (lengInt == 3) {
            aNumber += "000";
        } else if (lengInt < 0) {
            if (precision == 1) {
                aNumber += ".0";
            } else if (precision == 2) {
                aNumber += ".00";
            } else if (precision == 3) {
                aNumber += ".000";
            } else if (precision == 4) {
                aNumber += ".0000";
            }
            let ins = aNumber.toString().split(".");
            if (ins.length > 2) {
                aNumber = parseFloat(ins[0] + "." + ins[1]).toFixed(precision);
            }
        }
    }
    return aNumber;
}

/*
 * Function: 取字符串字节长度 Document by by 2007-3-9
 */
export const realLength = (str) => {
    let j = 0;
    for (let i = 0; i <= str.length - 1; i++) {
        j = j + 1;
        if ((str.charCodeAt(i)) > 127) {
            j = j + 1;
        }
    }
    return j;
}

// 中文作为3个字节处理
export const realLengthOnly = (str) => {
    let j = 0;
    for (let i = 0; i <= str.length - 1; i++) {
        j = j + 1;
        if ((str.charCodeAt(i)) > 127) {
            j = j + 2;
        }
    }
    return j;
}

//数字金额小写转大写
export const numberChangeToChinese = (num) => {
    let prefh = "";
    if (num === "") {
        return "";
    }
    if (!isNaN(num)) {
        if (num < 0) {
            prefh = "负";
            num = Math.abs(num);
        }
    }
    if (isNaN(num) || num > Math.pow(10, 12)) return "";
    let cn = "零壹贰叁肆伍陆柒捌玖";
    let unit = new Array("拾佰仟", "分角");
    let unit1 = new Array("万亿万", "");
    let numArray = num.toString().split(".");
    //  let start = new Array(numArray[0].length - 1, 2);

    const toChinese = (number, index, unit, start: number) => {
        let num = number.replace(/\d/g, ($1) => {
            return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1);
        });
        return num;
    }

    for (let i = 0; i < numArray.length; i++) {
        let tmp = "";
        for (let j = 0; j * 4 < numArray[i].length; j++) {
            let strIndex = numArray[i].length - (j + 1) * 4;
            let str = numArray[i].substring(strIndex, strIndex + 4);
            let start = i ? 2 : str.length - 1;
            let tmp1 = toChinese(str, i, unit, start);
            tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "");
            // tmp1 = tmp1.replace(/^壹拾/, "拾")
            tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp;
        }
        numArray[i] = tmp;
    }

    numArray[1] = numArray[1] ? numArray[1] : "";
    numArray[0] = numArray[0] ? numArray[0] + "圆" : numArray[0], numArray[1] = numArray[1].replace(/^零+/, "");
    numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整";
    let money = numArray[0] + numArray[1];
    money = money.replace(/(亿万)+/g, "亿");
    if (money == "整") {
        money = "零圆整";
    } else {
        money = prefh + money;
    }
    return money;
}


export const chineseChangeToNumber = (num) => {
    let prefh = "";
    if (num.length > 0) {
        if (num.indexOf("负") == 0) {
            prefh = "-";
            num = num.substr(1);
        }
    }

    let numArray = new Array()
    let unit = "万亿万圆$";
    for (let i = 0; i < unit.length; i++) {
        let re = eval("/" + (numArray[i - 1] ? unit.charAt(i - 1) : "") + "(.*)" + unit.charAt(i) + "/");
        if (num.match(re)) {
            // numArray[i] = num.match(re)[1].replace(/^拾/, "壹拾")
            numArray[i] = numArray[i].replace(/[零壹贰叁肆伍陆柒捌玖]/g, function ($1) {
                return "零壹贰叁肆伍陆柒捌玖".indexOf($1);
            });
            numArray[i] = numArray[i].replace(/[分角拾佰仟]/g, function ($1) {
                return "*" + Math.pow(10, "分角 拾佰仟 ".indexOf($1) - 2) + "+";
            }).replace(/^\*|\+$/g, "").replace(/整/, "0");
            numArray[i] = "(" + numArray[i] + ")*" + Math.ceil(Math.pow(10, (2 - i) * 4));
        }
        else numArray[i] = 0;
    }
    return prefh + eval(numArray.join("+"));
}

export const openUnFullWindow = (url, width, height, top, left) => {
    let szFeatures = "top=" + top + ",";
    szFeatures += "left=" + left + ",";
    szFeatures += "width=" + width + ",";
    szFeatures += "height=" + height + ",";
    szFeatures += "directories=no,";
    szFeatures += "status=yes,toolbar=no,location=no,";
    szFeatures += "menubar=no,";
    szFeatures += "scrollbars=yes,";
    szFeatures += "resizable=yes"; //channelmode
    window.open(url, "", szFeatures);
}

window.openUnFullWindow = openUnFullWindow;




//人力资源条件数据处理
export const spellResourceCondition = (datas) => {
    if (datas) {
        let value = [] as any[];
        datas.map((item) => {
            if (item.sharetype == "1") {
                value.push(`1_${item.relatedshare}_0_0`);
            } else if (item.sharetype == "2" || item.sharetype == "3") {
                value.push(`${item.sharetype}_${item.relatedshare}_0_${item.seclevel.replace('-', '|@|')}`);
            } else if (item.sharetype == "4") {
                value.push(`4_${item.relatedshare}_${item.rolelevel}_${item.seclevel.replace('-', '|@|')}`);
            } else if (item.sharetype == "5") {
                value.push(`5_0_0_${item.seclevel.replace('-', '|@|')}`);
            } else if (item.sharetype == "6") {
                if (item.joblevel == '2') {
                    value.push(`6_${item.relatedshare}_0_2|@|2`);
                } else {
                    value.push(`6_${item.relatedshare}_0_${item.joblevel}|@|${item.jobfield}`)
                }
            }
        });
        return value.join('~');
    }
    return '';
}
